package com.lagou.homework;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtils {

    // 1.定义成员变量
    public static DataSource dataSource;

    // 2.静态代码块
    static {

        try {
            // 3.创建属性集对象
            Properties p = new Properties();
            // 4. 加载配置文件 Druid 连接池不能够主动加载
            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("db.properties");
            // 5.使用properties对象的load 方法 从字节流中读取配置信息
            p.load(inputStream);
            // 6.通过工厂类获取连接对象
            DataSource dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取连接办法
    public static Connection getConnection() {

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static DataSource getDataSource() {
        return dataSource;
    }
    // 释放资源
    public static void close(Connection connection, Statement statement) {

        if(null != statement && null != connection) {
            try {
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {

        if(null != statement && null != connection && null != resultSet) {
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
